<template>
  <el-container>
    <el-header style="
        z-index: 90;
        padding: 0;
        margin: 0;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;

      ">
      <menu-bar></menu-bar>
    </el-header>
    <div style="margin: 60px 0 0 0;padding: 0;background-color: #f1f1f1">

      <Toolbar
          style="border: 1px solid #d5d5d5;
                position: fixed;
                z-index: 99;
                width: 100%;
                justify-content: center;
                "

          :editor="editor"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <el-form ref="titleForm" :model="article" :rules="titleRules" style=" width: 49%;
                     margin: 0 auto">
        <el-form-item prop="title">
          <el-input class="articleTitle"
                    style="background-color: #ffffff;
                     width: 100%;
                     margin: 50px auto 0 auto;
                     display: block;
                     height: 50px;
                      border-radius: 10px;
                    font-size: 16px;
 "
                    type="text"

                    v-model="article.title" placeholder="请输入文章标题"></el-input>
        </el-form-item>
      </el-form>

      <Editor
          style="width: 49%;
              height: 1000px;
              overflow-y: hidden;
              align-content: center;
              margin: 10px auto 20px auto;
             }"
          v-model="html"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="onCreated"
          @onChange="editorChange"
      >
      </Editor>

      <div style=" width: calc(49% - 60px);
                     margin: 0 auto 60px auto;
                       padding: 30px;
                     background-color: #FFFFFF;
                     ">
        <el-form ref="articleForm" :model="article" :rules="articleRules" label-width="80px"
                 style=" width: 100%;
                     background-color: #FFFFFF;
                     ">
          <el-form-item label="添加封面" prop="cover">
            <div v-show="!hideShow" style="width: 178px; height: 178px"
                 class="el-upload-list el-upload-list--picture-card">
              <div class="el-upload-list__item" style="width: 178px; height: 178px">
                <img  class="avatar" :src="imageUrl">
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-check"/>
                </label>
                <span class="el-upload-list__item-actions">
                  <span @click="handlePreview()">
                    <i class="el-icon-zoom-in"/>
                  </span>
                  <span class="el-upload-list__item-delete">
                    <i class="el-icon-delete" @click.stop="handleRemove()"/>
                  </span>
                </span>
              </div>
            </div>
            <el-upload
                v-show="hideShow"
                class="avatar-uploader"
                action="http://localhost:19090/article/upload-picture"
                name="picFile"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="选择分类" prop="categoryId">
            <el-select v-model="article.categoryId" placeholder="请选择分类">
              <el-option
                  v-for="item in category"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择民族" prop="nationId">
            <el-select filterable v-model="article.nationId" placeholder="请选择民族">
              <el-option
                  v-for="item in nation"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加简介" prop="synopsis">
            <el-input type="textarea" :rows="3" v-model="article.synopsis"></el-input>
          </el-form-item>
        </el-form>
      </div>


      <div style="height: 50px;
                background-color: #FFFFFF;
                position: fixed;
                z-index: 99;
                bottom: 0;
                width: 100%;
                line-height:50px;
                ">
        <el-button type="primary" round size="medium" style="margin-left: 70%" @click="saveArticle()">发布文章</el-button>

      </div>


    </div>
  </el-container>

</template>

<script>
import Vue from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import MenuBar from "@/components/MenuBar";
import PageFooter from "@/components/PageFooter";


export default {
  components: {MenuBar, PageFooter, Editor, Toolbar},
  data() {
    return {
      /*表格第一行*/
      headerBg: "headerBg",
      loading: false,

      windowsWidth: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,//兼容性获取屏幕高度
      /*wangEditor*/
      editor: null,
      html: '',
      currentHtml: {},


      toolbarConfig: {
        excludeKeys: [
          'group-video',
          'fullScreen'
        ]

      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: 'http://localhost:19090/article/upload-picture',
            fieldName: 'picFile',

            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 5 * 1024 * 1024, // 1M

            // 自定义插入图片
            customInsert(res, insertFn) {
              insertFn(res.data);
            },
          }
        }

      },
      mode: 'default', // or 'simple default'
      editorWidth: 500,
      nationDetailDTO: {},
      articleId: '',
      category: [],
      nation: [],
      article: {
        title: "",
        cover: "",
        synopsis: "",
        categoryId: "",
        content: "",
        nationId: '',
      },

      titleRules: {
        title: [
          {required: true, message: "请输入文章标题", trigger: "blur"},
          {min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur"},
        ],
      },


      articleRules: {

        cover: [
          {required: true, message: "请选择封面", trigger: "blur"},
        ],
        categoryId: [
          {required: true, message: "请选择分类", trigger: "blur"},
        ],
        synopsis: [
          {required: true, message: "请添加简介", trigger: "blur"},
        ],
        nationId: [
          {required: true, message: "请选择民族", trigger: "blur"},
        ],


      },
      imageUrl: '',
      uploadAvatar: '',
      hideShow: true,
      dialogImageUrl: '',
      dialogVisible: false,
    }

  },


  watch: {
    windowsWidth: {
      immediate: true,
      handler: function (newVal) {
        if (newVal >= 500 + 295) {
          this.editorWidth = newVal - 295;
        } else {
          this.editorWidth = 500;
        }

      }
    },
  },

  mounted() {
    window.onresize = () => {
      return (() => {
        this.windowsWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
      })()
    }

  },

  created() {
    this.getCategory();
    this.getNation();
  },

  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()

  },


  methods: {

    handleRemove() {

      this.axios.get("/article/remove-picture?pictureName=" + this.imageUrl).then(({data}) => {
        if (data.state == 20000) {
          this.$message.success(data.message);
        } else {
          this.$message.error(data.message);
        }
      });
      this.hideShow = !this.hideShow;
      this.imageUrl = '';

    },
    handlePreview() {
      this.dialogImageUrl = this.imageUrl;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      console.log("res:" + res.data)
      this.imageUrl = res.data;
      this.article.cover = this.imageUrl;
      this.hideShow = false;

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === "image/png";

      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }

      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },

    saveArticle() {
      this.$refs["articleForm"].validate((valid) => {
        if (valid) {
          this.article.title = this.article.title.trim();
          this.article.cover = this.article.cover.trim();
          this.article.synopsis = this.article.synopsis.trim();


          this.$refs["titleForm"].validate((valid) => {
            if (valid) {

              if (this.editor.getText().length < 10) {
                this.$message.error("文章内容过少,请重新编辑!");
              } else {
                this.category.forEach((item) => {
                  if (item.id == this.article.categoryId) {
                    this.article.categoryName = item.name;
                  }
                })
                this.article.content = this.editor.getHtml();
                this.axios.post("/article/insert-article", this.article).then(({data}) => {
                  if (data.state == 20000) {
                    this.articleId = data.data;
                    const loading = this.$loading({
                      lock: true,
                      text: '发布中',
                      spinner: 'el-icon-loading',
                      background: 'rgba(0, 0, 0, 0.7)'
                    });
                    setTimeout(() => {
                      loading.close();
                      this.$message.success(data.message);
                    }, 1000);
                    window.location.href = '/article/detail?id=' + data.data + "&nid=" + this.article.nationId;
                  } else {
                    this.$message.error(data.message);
                  }
                });
              }
            } else {
              this.$message.error("请添加标题!");
              return false;
            }
          })


        } else {
          this.$message.error("提交失败");
          return false;
        }
      })

    },

    checkEditor() {


    },

    editorChange() {

    },

    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // editor.disable();

    },

    clearHtml() {
      this.html = '';
    },


    getCategory() {
      this.axios.get("/category/get-all-list").then(({data}) => {
        if (data.state == 20000) {
          this.category = data.data;
        } else {
          this.$message.error(data.message);
        }
      });
    },

    getNation() {
      this.axios.get("/nation/get-all-list").then(({data}) => {
        if (data.state == 20000) {
          this.nation = data.data;
        } else {
          this.$message.error(data.message);
        }
      });
    },


  },


}
</script>

<style src="@wangeditor/editor/dist/css/style.css"/>

<style>


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;

}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


.articleTitle .el-input {
  position: relative;
  font-size: 16px;
  border-radius: 10px;
}

.el-input {
  border-radius: 10px;
  border: 1px solid #DCDFE6;
}

.articleTitle .el-input__inner {
  -webkit-appearance: none;
  background-color: #FFF;
  background-image: none;
  border-radius: 10px;
  border: 1px solid #DCDFE6;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  height: 50px;
  line-height: 50px;
  outline: 0;
  padding: 0 15px;
  transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
  width: 100%;
}


.headerBg {
  background: #eee !important;
}

.el-dialog__body {
  padding: 0px 20px;
  color: #606266;
  font-size: 16px;
  word-break: break-all;

}

.menu[data-v-e3a2c392] {
  padding: 0;
}
</style>
